﻿var onload = false;
var sep2 = ',';
var IsCheckedDefault = false;
var IsEditing = false;

$(function() {
    if (!$.cookie('HideDetail'))
        $.cookie('HideDetail', 'none');
    $('.hide').css('display', $.cookie('HideDetail'));
    $(".TableGrid tr").mouseover(function() { $(this).addClass("over"); }).mouseout(function() { $(this).removeClass("over"); });
    $(".TableGrid tr:even").addClass("alt");
    $('#pageSize').keydown(function(event) {
        if (event.keyCode == 13) {
            var value = document.getElementById('pageSize').value;
            if (isNaN(value) == false)
                $('#Page').attr('value', '1');
            $('.required').removeAttr('min');
            $('.required').removeClass('required');
            $('form').submit();
        }
    });
    $('#checkAll').click(function() {
        $("INPUT[type='checkbox'][group='Selected']").each(function() {
            if ($(this).parent().parent().parent().parent().parent().attr("group") != "Except")
                $(this).attr('checked', $('#checkAll').is(':checked'));
        })


        if ($('#checkAll').attr('checked') == true) {
            $('.TableGrid tr').each(function(index) {
                var isDefault = $($(this).find("input[type='checkbox'][class='IsDefault']")).attr('disabled');
                if (isDefault == true) {
                    IsCheckedDefault = true;
                    return;
                }
            });
        }
        else
            IsCheckedDefault = false;
    });

    if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
        $(".NavCt br").remove();
        $(".mainNav").css('height', '20px');
        $(".subNav").css('height', '10px');
        $(".subNav").css('margin-bottom', '0px');
    }
    if ($.browser.msie && $.browser.version.substr(0, 1) == 7) {
        $(".NavCt br").last().remove();
        $(".mainNav").css('padding-bottom', '5px');
        $(".subNav").css('height', '20px');
        $(".subNav").css('margin-bottom', '0px');
    }


    $('form input[type="text"],input[type="checkbox"],input[type="button"],select,textarea,a,th,#messageBox,.errorMessage,.successBox').click(function() {
        $('#messageBox,.errorMessage,.successBox').css('display', 'none');
        $('.advanceSearchBox').css('padding-bottom','0px');
        $('.linedot').css('padding-bottom','3px');
    });
    
    $("#Submit").click(function() {
        $("form").submit();
    });
    
    //Set ScrollBar While Resizing
    $('.flexigrid').resize(function(){
   
    $(this).find('.hDiv').scrollLeft($(this).find('.bDiv').scrollLeft());
        //$(this '.hDiv').scrollLeft($('.bDiv').scrollLeft());
    });
});

function Uncheck(id) {
    //var selected = document.getElementById(id);
    var selected = $("#" + id);
    //if (selected.checked != 'checked') {
    if (selected.is(':checked') == false) {
        if (id == 'InvoiceID')
            $("INPUT[type='checkbox'][id='InvCheckAll']").removeAttr('checked');
        else if (id == 'ShipmentID')
            $("INPUT[type='checkbox'][id='SpCheckAll']").removeAttr('checked');
        else
            $("INPUT[type='checkbox'][id='checkAll']").removeAttr('checked');
    }
}

function paging(value, pageNum) {
    if (value > 0 && value <= pageNum) {
        $('#Page').attr('value', value);
        $('.required').removeAttr('min');
        $('.required').removeClass('required');
        $('form').submit();
    }
}


function toggleDiv(id) {
    var state = document.getElementById(id).style.display;
    if (state == 'block') {
        document.getElementById(id).style.display = 'none';
        $('a.advanceSearch').addClass('plus');
        $('a.advanceSearch').removeClass('minus');
        $('#IsAdvSearch').attr('value', 'false');
    }
    else {
        document.getElementById(id).style.display = 'block';
        $('a.advanceSearch').addClass('minus');
        $('a.advanceSearch').removeClass('plus');
        $('#IsAdvSearch').attr('value', 'true');
    }
}

function togglePanels(id, obj) {
    var state = $('#' + id).css('display');
    if (state == 'block') {
        $('#' + id).css('display', 'none');
        $('#' + obj).addClass('plus');
        $('#' + obj).removeClass('minus');
    }
    else {
        $('#' + id).css('display', 'block');
        $('#' + obj).addClass('minus');
        $('#' + obj).removeClass('plus');
    }
    //$.cookie('Display' + id, $('#' + id).css('display'));
}

function Cancel() {
    window.location = window.location;
}

function DoUrl(url) {
    window.location = url;
}

function Add(param1, param2) {
    if (param2 == null) {
        window.location = "Add" + param1;
    }
    else if (isNaN(param2) == false && param2 != null) {
        window.location = "../Add/" + param2;
    }
    else
        window.location = "Add";
}

function ViewEdit(param) {
    window.location = param;
}

function DoAction(param) {
    var checked = $("input[group='Selected']:checked").length;
    if (checked > 1 || checked == 0)
        return -1;
    else {
        $.cookie('SelectedItem', $("input[group='Selected']:checked").val());
        window.location = param + '/' + $("input[group='Selected']:checked").val();
    }
}

function Edit(param, param2) {
    var checked = $("input[group='Selected']:checked").length;
    if (checked > 1 || checked == 0)
        return -1;
    else {
        $.cookie('SelectedItem', $("input[group='Selected']:checked").val());
        window.location = param + '/' + $("input[group='Selected']:checked").val();
    }
}

function Replicate(param, param2) {
    var checked = $("input[group='Selected']:checked").length;
    if (checked > 1 || checked == 0)
        return -1;
    else {
        $.cookie('SelectedItem', $("input[group='Selected']:checked").val());
        window.location = param + '/' + $("input[group='Selected']:checked").val();
    }
}

function Substitute(param) {
    var checked = $("input[group='Selected']:checked").length;
    if (checked > 1 || checked == 0)
        return -1;
    else
        window.location = param + "/" + $("input[group='Selected']:checked").val();
}

function Replenish(param) {
    var checked = $("input[group='Selected']:checked").length;
    if (checked > 1 || checked == 0)
        return -1;
    else
        window.location = param + "/" + $("input[group='Selected']:checked").val();
}
$(function() {
    $(".TableGrid th").click(function() {
        if ($(this).parent().parent().parent().attr("group") == 'Exception')
            return;
        if ($(this).parent().parent().parent().attr("group") == 'NoSort')
            return;
        if($('#IsPrint').attr('id'))
            $('#IsPrint').val('false');
        var id = this.id;
        var orderBy = $('#orderBy');
        var orderDirection = $('#orderDirection');
        if (id == 'Selected') {
            //  $("INPUT[type='checkbox'][group='Selected']").attr('checked', $('#checkAll').is(':checked'));
        }
        else if (id == 'A_Selected') {
            $("INPUT[type='checkbox'][group='A_Selected']").attr('checked', $('#AcheckAll').is(':checked'));
        }
        else if (id == 'L_Selected') {
            $("INPUT[type='checkbox'][group='L_Selected']").attr('checked', $('#LcheckAll').is(':checked'));
        }
        else if (id == 'Order' || id == 'InvOrder' || id == 'SpOrder' || id == '') {
        }
        else {
            if (orderBy.val() == id) {
                if ($('#orderDirection').val() == 'ASC')
                    $('#orderDirection').attr('value', 'DESC');
                else
                    $('#orderDirection').attr('value', 'ASC');
            }
            else {
                $('#orderDirection').attr('value', 'ASC');
                $('#orderBy').attr('value', id);
            }
            if ($('form').attr('id') == 'formAddOrderLine') {
                $('#ListAction').attr('value', 'true');
                $("#formAddOrderLine").validate().cancelSubmit = true;
                submitErr = false;
                submitErr2 = false;
            }

            $('#Action').val('');
            $('.required').removeAttr('min max');
            $('.required').removeClass('required');
            $('form').submit();
        }

    });
});

$(function() {
    $(".DENumber").filter_inputDecimal('.');
    $(".DENumber").loadFormatDecimal('.');

    $(".PhoneFax").filter_input({ regex: '0123456789+-' });

});



var submitErr = false;
var submitErr2 = false;
$(function() {
    $('form').validate({
        invalidHandler: function(e, validator) {
            var errors = validator.numberOfInvalids();
            if (errors > 0 && onload == true) {
                $('#messageBox,.errorMessage').css('display', 'block');
                $('#messageBox,.errorMessage').addClass('errorBox');
                $('#messageBox,.errorMessage').html('You missed ' + errors + ' fields.  They have been highlighted above!');
                submitErr = true;
                submitErr2 = true;
            }
        },
        focusInvalid: funfalse
    });
    $('form').reverseDefaultDecimalFormat('.', "DENumber");
    $('form').load();
    onload = true;
});





(function($) {
    $.fn.extend({
        formatDecimal: function(sep) {
            var allItem = $(this);
            $.each(allItem, function() {
                $(this).html(FormatNumber($(this).html(), sep));
                $(this).parent().css("text-align", "right");
            });
        }
    });
})(jQuery);

(function($) {
    $.fn.extend({
        loadFormatDecimal: function(sep) {
            var allItem = $(this);
            $.each(allItem, function() {
                $(this).val(FormatNumber($(this).val(), sep));
            });
        }
    });
})(jQuery);

function FormatNumberOnKeyUp(nStr, sep) {
    nStr = jQuery.trim(nStr.toString());
    if (sep == '.')
        sep2 = ',';
    if (sep == ',')
        sep2 = '.';
    nStr += '';
    pos = nStr.lastIndexOf(sep2);
    while (pos >= 0) {
        nStr = nStr.replace(sep2, "");
        pos = nStr.lastIndexOf(sep2);
    }
    var x = nStr.split(sep);
    var x1 = x[0];
    var x2 = x.length > 1 ? sep + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + sep2 + '$2');
    }
    return x1 + x2;
}

function FormatNumber(nStr, sep) {
    nStr = jQuery.trim(nStr.toString());
    //nStr = nStr.toFixed(2).toString();
    if (sep == '.')
        sep2 = ',';
    if (sep == ',')
        sep2 = '.';
    nStr += '';
    pos = nStr.lastIndexOf(sep2);
    while (pos >= 0) {
        nStr = nStr.replace(sep2, "");
        pos = nStr.lastIndexOf(sep2);
    }
    var x = nStr.split(sep);
    var x1 = x[0];
    var x2 = x.length > 1 ? sep + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + sep2 + '$2');
    }
//    if (x2 == (sep + '00'))
//        x2 = '';
    return x1 + x2;
}

function checkAccept(keyCode) {
    var acceptKey = new Array(0, 8, 9, 11, 13, 46, 79, 247);
    for (i = 0; i < acceptKey.length; i++) {
        if (acceptKey[i] == keyCode)
            return true;
    }
}

function checkAcceptNonNegative(keyCode) {
    var acceptKey = new Array(13, 8, 9, 11, 37, 39, 46, 36, 247, 79, 35, 38, 40);
    for (i = 0; i < acceptKey.length; i++) {
        if (acceptKey[i] == keyCode)
            return true;
    }
}

(function($) {
    $.fn.extend({
        filter_inputDecimal: function(sep) {
            //            $(this).filter_inputDecimalId(sep);
            $(this).each(function() {
                var input = $(this);
                $(this).keyup(function(event) {
                    if (checkAccept(event.keyCode) && event.keyCode != 8 && event.keyCode != 46) return true;
                    var value = input.val();

                    //$('div.clockdate').html($('div.clockdate').html() + '-' + value );
                    input.val(FormatNumberOnKeyUp(value, sep));
                });
                $(this).keypress(function(e) {
                    var key = window.event ? e.keyCode : e.which;
                    var keychar = parseInt(String.fromCharCode(key));

                    var reg = /\d/;
                    if (reg.test(keychar) || checkAccept(key))
                        return true;

                    e.preventDefault();

                });
                $(this).change(function() {
                    var nStr = input.val();
                    while (nStr.charAt(0) == '0' && nStr.charAt(1) != sep && nStr.length > 1)
                        nStr = FormatNumberOnKeyUp(nStr.substring(1, nStr.length), sep);

                    if (nStr[nStr.length - 1] == sep)
                        nStr = nStr.substring(0, nStr.length - 1);
                    //$('div.clockdate').html($('div.clockdate').html() + '-' + nStr);
                    input.val(FormatNumberOnKeyUp(nStr, sep));
                });
                $(function() {
                    $(this).change();
                });
            });
        }
    });
})(jQuery);


//var shortMonth= new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

function format(str) {
    for (i = 0; i < arguments.length - 1; i++) {
        str = str.replace('{' + (i) + '}', arguments[i + 1]);
    }
    return str;
}

function getFormat(format) {
    format = format.toLowerCase();
    pos21 = format.indexOf("m");
    pos22 = format.lastIndexOf("m");
    mm = format.substring(pos21, pos22 + 1);
    if (mm.length == 3)
        mformat = "aaa";
    else
        mformat = "99";
    return new Array("99", mformat, "9999");
}


function getDateTimeDefaultFormat(format, datetime) {
    if (datetime.length < 4)
        return '';
    format = format.toLowerCase();
    pos11 = format.indexOf("d");
    pos12 = format.lastIndexOf("d");
    pos21 = format.indexOf("m");
    pos22 = format.lastIndexOf("m");
    pos31 = format.indexOf("y");
    pos32 = format.lastIndexOf("y");
    sep = "/";
    return datetime.substring(pos31, pos32 + 1) + sep + datetime.substring(pos21, pos22 + 1) + sep + datetime.substring(pos11, pos12 + 1)
}


function toMaskedFormat(dateFormat) {
    arr1 = getFormat(dateFormat);
    arr2 = getPos(dateFormat);
    sep = getSep(dateFormat);
    return format('{0}' + sep + '{1}' + sep + '{2}', arr1[arr2[0]], arr1[arr2[1]], arr1[arr2[2]])
}

function getPos(format) {
    format = format.toLowerCase();
    pos1 = format.lastIndexOf("d");
    pos2 = format.lastIndexOf("m");
    pos3 = format.lastIndexOf("y");
    if (pos1 > pos2) {
        if (pos2 > pos3) {
            return new Array(2, 1, 0);
        }
        else if (pos2 < pos3) {
            if (pos1 > pos3) {
                return new Array(2, 0, 1);
            }
            else if (pos1 < pos3) {
                return new Array(1, 0, 2);
            }
        }
    }
    else if (pos1 < pos2) {
        if (pos2 < pos3) {
            return new Array(0, 1, 2);
        }
        else if (pos2 > pos3) {
            if (pos1 > pos3) {
                return new Array(1, 2, 0);
            }
            else if (pos1 < pos3) {
                return new Array(0, 2, 1);
            }
        }
    }
}
function getSep(format) {
    format = format.toLowerCase();
    for (i = 1; i < format.length; i++) {
        if (format.charAt(0) != format.charAt(i))
            return format.charAt(i);
    }
}



(function($) {
    $.fn.extend({
        reverseDefaultDateTimeFormat: function(format, cls) {
            var form = $(this);
            form.submit(function() {

                var inputAll = $('.' + cls);
                $.each(inputAll, function(k, input) {
                    var id = '#' + input.id.toString();
                    var value = $(id).val();
                    if (submitErr == false && value.length > 3)
                        $(id).val(getDateTimeDefaultFormat(format, value));
                });
                submitErr = false;
            });
        }
    });
})(jQuery);


(function($) {
    $.fn.extend({
        reverseDefaultDecimalFormat: function(sep, cls) {

            var form = $(this);
            form.submit(function() {

                if (sep == '.')
                    sep2 = ',';
                if (sep == ',')
                    sep2 = '.';

                var inputAll = $('.' + cls);
                $.each(inputAll, function(k, input) {
                    if (submitErr2 == false) {
                        var id = '#' + input.id.toString();
                        var value = $(id).val();
                        while (value.lastIndexOf(sep2) >= 0) {
                            value = value.replace(sep2, "");
                        }
                        $(id).val(value);
                    }
                });
                submitErr2 = false;
            });
        }
    });
})(jQuery);


function formatConvert(format) {
    format = format.toLowerCase();
    format = format.replace("yyyy", "yy");
    format = format.replace("mmm", "M");
    return format;
}

(function($) {

    $.fn.extend({
        filter_input: function(options) {
            var defaults = {
                regex: ".*"
            }
            var options = $.extend(defaults, options);
            return this.each(function() {
                var input = $(this);
                var regex = options.regex;
                input.keypress(function(event) {
                    var key = event.charCode ? event.charCode : event.keyCode ? event.keyCode : 0;
                    if (checkAccept(key)) return true;
                    var string = String.fromCharCode(key);
                    if (regex.match(string)) {
                        return true;
                    }
                    return false;
                });
            });
        }
    });

})(jQuery);


function DatePicker(id) {
    if($("#" + id).is(':disabled'))
        return;
    $("#" + id).datepicker("enable");
    $("#" + id).datepicker({
        dateFormat: userDateFormat,
        gotoCurrent: true,
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        hideIfNoPrevNext: true,
        onClose: function() {
            $("#" + id).datepicker("destroy");
        }
    });
    $("#" + id).datepicker("show");
}

$(function() {
    windowsWidth = document.body.offsetWidth;
    windowsWidth = windowsWidth - 270;
    //$('.TableGrid').flexigrid({ width: windowsWidth, onChangeSort: true });
    $(".DeNumber").formatDecimal('.');
});

function updateClock() {

    currentSeconds = currentSeconds * 1 + 1;
    currentMinutes = currentMinutes * 1;
    currentHours = currentHours * 1;

    if (currentSeconds == 60) {
        currentSeconds = 0;
        currentMinutes = currentMinutes + 1;
    }
    if (currentMinutes == 60) {
        currentMinutes = 0;
        currentHours = currentHours + 1;
    }

    currentHours = (currentHours == 24) ? currentHours - 24 : currentHours;

    currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
    currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
    currentHours = (currentHours < 10 ? "0" : "") + currentHours;
    var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds;
    $("#clock").html(currentTimeString);
}

$(function() {
    $(window).resize(function() {
        var display = document.getElementById('LeftCol').style.display;
        if (display == 'none') {
            var width = $(window).width() - 50;
            $('.flexigrid').width(width);
            $('.hDiv').width(width);
            $('.bDiv').width(width - 2);
        }
        else {
            var width = $(window).width() - 270;
            $('.flexigrid').width(width);
            $('.hDiv').width(width);
            $('.bDiv').width(width - 2);

        }

    });

    $(window).resize();
    $('.flexigrid').each(function() {
        var f = $(this);
        f.find('.bDiv').scroll(function() {
            f.find('.hDiv').scrollLeft(f.find('.bDiv').scrollLeft());
        });
    });
});


(function($) {
    $.fn.extend({
        HightLightSelected: function() {
            if ($(this).attr("group") == "Exception")
                return;
            $("input[group='Selected'][value='" + $.cookie('SelectedItem') + "']").parent().parent().parent().addClass('trSelected');
            $("input[group='InvSelected'][value='" + $.cookie('SelectedItem') + "']").parent().parent().parent().addClass('trSelected');
            $("input[group='BOSelected'][value='" + $.cookie('SelectedItem') + "']").parent().parent().parent().addClass('trSelected');
            $("input[group='A_Selected'][value='" + $.cookie('SelectedItem') + "']").parent().parent().parent().addClass('trSelected');
            $("input[group='L_Selected'][value='" + $.cookie('SelectedItem') + "']").parent().parent().parent().addClass('trSelected');
            $.cookie('SelectedItem', null);
            var Table = $(this);
            if (Table.find('tr th').length > 0) return;
            Table.find('tr td input[group="Selected"]').click(function() {
                if ($(this).is(':checked')) {
                    $(this).removeAttr('checked');
                    $(this).parent().parent().parent().removeClass('trSelected');
                }
                else {
                    $(this).attr('checked', 'checked');
                    $(this).parent().parent().parent().addClass('trSelected');
                }

                $('#checkAll').removeAttr('checked');
                $('#AcheckAll').removeAttr('checked');
                $('#LcheckAll').removeAttr('checked');

            });
            Table.find('tr td input[group="InvSelected"]').click(function() {
                if ($(this).is(':checked')) {
                    $(this).removeAttr('checked');
                    $(this).parent().parent().parent().removeClass('trSelected');
                }
                else {
                    $(this).attr('checked', 'checked');
                    $(this).parent().parent().parent().addClass('trSelected');
                }

                $('#checkAll3').removeAttr('checked');
            });
            Table.find('tr td input[group="BOSelected"]').click(function() {
                if ($(this).is(':checked')) {
                    $(this).removeAttr('checked');
                    $(this).parent().parent().parent().removeClass('trSelected');
                }
                else {
                    $(this).attr('checked', 'checked');
                    $(this).parent().parent().parent().addClass('trSelected');
                }

                $('#checkAll3').removeAttr('checked');
            });

            Table.find('tr').click(function() {
                if ($(this).attr('class').match("trSelected")) {
                    $(this).removeClass('trSelected');
                    if ($(this).find("td input[group='Selected']").attr('id')) {
                        
                        checkbox = $(this).find("td input[group='Selected']");
                        
                        if (checkbox.is(':checked')) {
                            checkbox.removeAttr('checked');
                            var isDefault = $($(this).find("input[type='checkbox'][class='IsDefault']")).attr('disabled');

                            if (isDefault)
                                IsCheckedDefault = false;
                        }
                        else {
                            checkbox.attr('checked', 'checked');
                            $(this).addClass('trSelected');
                            var isDefault = $($(this).find("input[type='checkbox'][class='IsDefault']")).attr('disabled');

                            if (isDefault)
                                IsCheckedDefault = true;
                        }
                        $('#checkAll').removeAttr('checked');
                    }

                    if ($(this).find("td input[group='InvSelected']").attr('id')) {
                        checkbox = $(this).find("td input[group='InvSelected']");

                        if (checkbox.is(':checked')) {
                            checkbox.removeAttr('checked');
                            var isDefault = $($(this).find("input[type='checkbox'][class='IsDefault']")).attr('disabled');

                            if (isDefault)
                                IsCheckedDefault = false;
                        }
                        else {
                            checkbox.attr('checked', 'checked');
                            $(this).addClass('trSelected');
                            var isDefault = $($(this).find("input[type='checkbox'][class='IsDefault']")).attr('disabled');

                            if (isDefault)
                                IsCheckedDefault = true;
                        }
                    }

                    if ($(this).find("td input[group='BOSelected']").attr('id')) {
                        checkbox = $(this).find("td input[group='BOSelected']");

                        if (checkbox.is(':checked')) {
                            checkbox.removeAttr('checked');
                            var isDefault = $($(this).find("input[type='checkbox'][class='IsDefault']")).attr('disabled');

                            if (isDefault)
                                IsCheckedDefault = false;
                        }
                        else {
                            checkbox.attr('checked', 'checked');
                            $(this).addClass('trSelected');
                            var isDefault = $($(this).find("input[type='checkbox'][class='IsDefault']")).attr('disabled');

                            if (isDefault)
                                IsCheckedDefault = true;
                        }
                        $('#checkAll3').removeAttr('checked');
                    }
                }
                else {
                    $(this).addClass('trSelected');
                    $(this).find("td input[group='Selected']").attr('checked', 'checked');
                    $(this).find("td input[group='InvSelected']").attr('checked', 'checked');
                    $(this).find("td input[group='BOSelected']").attr('checked', 'checked');

                    var isDefault = $($(this).find("input[type='checkbox'][class='IsDefault']")).attr('disabled');
                    if (isDefault)
                        IsCheckedDefault = true;
                }

            });
        }
    });
})(jQuery);

(function($) {
    $.fn.extend({
        HightLightSelectedNoCheckbox: function() {
            var Table = $(this);
            Table.find('tr').click(function() {
                if ($(this).attr('class').match("trSelected")) {
                    $(this).removeClass('trSelected');
                }
                else {
                    $(this).addClass('trSelected');
                }
            });
        }
    });
})(jQuery);
$(function() {
    $('.TableGrid').each(function() {
        $(this).HightLightSelected();
    });
    $("#checkAll").change(function() {
        $(".TableGrid td input[type='checkbox'][group='Selected']").each(function() {
            if ($(this).is(":checked"))
                $(this).parent().parent().parent().addClass('trSelected');
            else
                $(this).parent().parent().parent().removeClass('trSelected');
        });
    });

});

function formatJSONDate(jsonDate) {
    if(jsonDate != null)
    {
        var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
        var newDate = dateFormat(date, userDateFormat.replace("yy", "yyyy"));
        return newDate;
    }
    return '';
}

function WriteTD(value, width, align) {
    var str = '<td><div style="';
    if (align != undefined)
        str = str + 'text-align: ' + align + '; ';
    if (width == undefined)
        width = 150;
    if (value == null)
        value = "";

    str = str + 'width: ' + width + 'px;">' + value + '</div></td>';
    return str;
}

function togglePanel(editRole) {
    if (editRole.checked == true)
        $('#EditRole').css('display', 'block');
    else
        $('#EditRole').css('display', 'none');
}

function AddOne() {
    var Roles = $("option:selected", $('#available'));
    $.each(Roles, function(index, opt) {
        $("#SelectedRole").append(opt);
    });
}
function AddAll() {
    var Roles = $("option", $('#available'));
    $.each(Roles, function(index, opt) {
        $("#SelectedRole").append(opt);
    });
}

function RemoveOne() {
    var Roles = $("option:selected", $('#SelectedRole'));
    $.each(Roles, function(index, opt) {
        $("#available").append(opt);
    });
}
function RemoveAll() {
    var Roles = $("option", $('#SelectedRole'));
    $.each(Roles, function(index, opt) {
        $("#available").append(opt);
    });
}

$(function() {
    $('.SpeChar').filter_specialCharacter();
});

(function($) {
    $.fn.extend({
        filter_specialCharacter: function() {
            $(this).keypress(function(e) {
                var key = window.event ? e.keyCode : e.which;
                var keychar = String.fromCharCode(key);
                var regex = /[~`!@#\$%\^&\*\\{}\[\];\?<>|//]/;

                if (!regex.test(keychar) || checkAccept(key)) {
                    return true;
                }
                e.preventDefault();
            });
        }
    });
})(jQuery);


function ResetIsCheckedDefault() {
    IsCheckedDefault = false;
}

function CheckIsCheckedDefault(obj) {
    var isDefault = $(obj).find("td input[type='checkbox'][class='IsDefault']").attr('disabled');
    if (isDefault)
        IsCheckedDefault = true;
}


function stepSelect(id, direction) {
    if (direction == 'up') {
        $('#' + id + ' option:selected').next().attr('selected', 'selected');
    }
    if (direction == 'down') {
        $('#' + id + ' option:selected').prev().attr('selected', 'selected');
    }
    $('#' + id).change();
};

function msieversion() {
            var ua = window.navigator.userAgent
            var msie = ua.indexOf("MSIE ")

            if (msie > 0)      // If Internet Explorer, return version number
                return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)))
            else                 // If another browser, return 0
                return 0
}

function Clear(obj) {
    $('.maincontent input[type="text"]').val('');
    $('#' + obj + '').val('');
    $('.maincontent select').val('0');
    $('#OldAction').val('');
    $('#Action').val('');
    $('.changeable').attr('disabled', 'disabled');
    
}

// ListObject to input: ex: '.PaymentAmount'
function SumData(listObject)
{
    var Sum = 0;
    $(listObject).each(function() {
        Sum += parseFloat($(this).val().replace(/,/g, ''));
    });
    return Sum;
}


function SumDataAndValidate(listObject)
{
    var Sum = 0;
    var Item = 0;
    $(listObject).each(function() {
        Item = parseFloat($(this).val().replace(/,/g, ''));
        if(Item <= 0)
            return 0;
        Sum += Item;
    });
    return Sum;
}

//Get,Set Value to Int CheckBox
function SetIntCheckBox(objectID, value, hiddenID){
    if(hiddenID == null)
    {
        hiddenID = 'h' + objectID;
    }
    
    if (value == '1')
    {
        $("#" + objectID).attr('checked', 'checked');
        $('#' + hiddenID).val(1);
    }
    else
    {
        $("#" + objectID).removeAttr('checked');
        $('#' + hiddenID).val(0);
    }
    
    $("#" + objectID).click(function() {
        if ($("#" + objectID).is(':checked'))
            $('#' + hiddenID).attr("value", "1");
        else
            $('#' + hiddenID).attr("value", "0");
    });
}

function GetIntCheckBox(objectID, hiddenID){
    if(hiddenID == null)
    {
        hiddenID = 'h' + objectID;
    }
    
    if ($('#' + objectID).is(':checked'))
    {
        $('#' + hiddenID).val(1);
    }
    else
    {
        $('#'+ hiddenID).val(0);
    }
}
//END Get,Set Value to Int CheckBox
// function validateDate(dtControl) {
//        var input = document.getElementById(dtControl)
//        if(input.value == '') return
//        var validformat = /^\d{1,2}\/\d{1,2}\/\d{4}$/ //Basic check for format validity
//        var returnval = false
//        if (!validformat.test(input.value))
//        {
//            alert('Invalid Date Format. Please correct.')
//            input.value = ''
//        }
//        else { //Detailed check for valid date ranges
//            var dayfield = input.value.split("/")[0]
//            var monthfield = input.value.split("/")[1]
//            var yearfield = input.value.split("/")[2]

//            var dayobj = new Date(yearfield, monthfield - 1, dayfield)
//            if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield)) {
//                alert('Invalid Day, Month, or Year range detected. Please correct.')
//               
//            }
//            else {
//                returnval = true
//            }
//        }
//        if (returnval == false) input.focus()
//        return returnval
//}

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
    return pattern.test(emailAddress);
};



